# updater.ps1
param(
    [string]$LocalVersion,
    [string]$VersionUrl,
    [string]$CurrentScriptPath
)

$tempDir = $env:TEMP
$versionFile = Join-Path $tempDir "version.txt"
$newScriptFile = Join-Path $tempDir "new_auto_installer.bat"

Write-Host "正在检查脚本更新..." -ForegroundColor Cyan
Write-Host "(如果60秒内无响应将自动跳过)" -ForegroundColor DarkGray

# 清理旧的临时文件，防止缓存问题
Remove-Item $versionFile -ErrorAction SilentlyContinue
Remove-Item $newScriptFile -ErrorAction SilentlyContinue

$maxRetries = 3 # 最大重试次数
$retryDelay = 5 # 每次重试间隔秒数

# --- 下载版本信息文件 ---
for ($i = 0; $i -lt $maxRetries; $i++) {
    try {
        Write-Host "正在从 $VersionUrl 下载版本信息 (尝试 $((i+1))/$maxRetries)..." -ForegroundColor Green
        Invoke-WebRequest -Uri $VersionUrl -OutFile $versionFile -TimeoutSec 60 -ErrorAction Stop
        break # 下载成功，跳出重试循环
    } catch {
        Write-Host "警告：获取远程版本信息失败（网络错误或超时）。" -ForegroundColor Yellow
        if ($i -lt ($maxRetries - 1)) {
            Write-Host "将在 $retryDelay 秒后重试..." -ForegroundColor Yellow
            Start-Sleep -Seconds $retryDelay
        } else {
            Write-Host "已达到最大重试次数，将使用本地版本。" -ForegroundColor Yellow
            exit 0 # 达到最大重试次数，退出并继续批处理脚本
        }
    }
}

$remoteVersion = ""
$scriptUrl = ""

try {
    Get-Content $versionFile -Encoding UTF8 | ForEach-Object {
        if ($_ -match "^REMOTE_VERSION=(.*)$") {
            $remoteVersion = $matches[1]
        }
        if ($_ -match "^SCRIPT_URL=(.*)$") {
            $scriptUrl = $matches[1]
        }
    }
} catch {
    Write-Host "警告：读取版本文件失败。" -ForegroundColor Yellow
    exit 0 # 无更新，继续批处理脚本
}

if (-not $remoteVersion) {
    Write-Host "警告：版本文件格式错误，无法读取远程版本。" -ForegroundColor Yellow
    exit 0 # 无更新，继续批处理脚本
}

Write-Host "当前版本: $LocalVersion" -ForegroundColor White
Write-Host "最新版本: $remoteVersion" -ForegroundColor White

if ($LocalVersion -eq $remoteVersion) {
    Write-Host "脚本已是最新版本。" -ForegroundColor Green
    Remove-Item $versionFile -ErrorAction SilentlyContinue
    exit 0 # 无更新，继续批处理脚本
}

Write-Host "发现新版本！准备自动更新..." -ForegroundColor Yellow
Write-Host "新脚本下载地址: $scriptUrl" -ForegroundColor DarkCyan

# --- 下载新版本脚本 ---
for ($i = 0; $i -lt $maxRetries; $i++) {
    try {
        Write-Host "正在下载新版本脚本 (尝试 $((i+1))/$maxRetries)..." -ForegroundColor Green
        Invoke-WebRequest -Uri $scriptUrl -OutFile $newScriptFile -TimeoutSec 60 -ErrorAction Stop
        break # 下载成功，跳出重试循环
    } catch {
        Write-Host "错误：下载新版本脚本失败。" -ForegroundColor Red
        if ($i -lt ($maxRetries - 1)) {
            Write-Host "将在 $retryDelay 秒后重试..." -ForegroundColor Yellow
            Start-Sleep -Seconds $retryDelay
        } else {
            Write-Host "已达到最大重试次数，无法更新。" -ForegroundColor Red
            exit 0 # 达到最大重试次数，退出并继续批处理脚本
        }
    }
}

Write-Host "新版本下载完成，脚本将自动替换并重启。" -ForegroundColor Green
Start-Sleep -Seconds 3

try {
    Copy-Item -Path $newScriptFile -Destination $CurrentScriptPath -Force -ErrorAction Stop
    Remove-Item $versionFile -ErrorAction SilentlyContinue
    Remove-Item $newScriptFile -ErrorAction SilentlyContinue
    Write-Host "更新完成，正在重启脚本..." -ForegroundColor Green
    Start-Process -FilePath $CurrentScriptPath
    exit 1 # 指示批处理脚本退出
} catch {
    Write-Host "错误：应用更新失败。" -ForegroundColor Red
    exit 0 # 无更新，继续批处理脚本
}